package com.elitel.frame.base.component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间延时推算工具类
 */
public class TimeDelay {

    private static final DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    /**
     * TODO: 根据
     * @param conQueryStr
     * @param queryFiledsStr
     * @param delayTime
     * @return
     * @throws ParseException
     */
    public static String delay(String conQueryStr, String queryFiledsStr, int delayTime) throws ParseException {
        JSONObject conQueryObj = (JSONObject) JSONObject.parse(conQueryStr);
        JSONArray queryFileds = JSONArray.parseArray(queryFiledsStr);

        if (conQueryObj !=null && queryFileds !=null && conQueryObj.size() > 0 && queryFileds.size() > 0) {
            for (int i = 0; i < queryFileds.size(); i++) {
                JSONObject queryFiled = (JSONObject) queryFileds.get(i);
                String filed = queryFiled.getString("parametercode");

                // 只对日期类型格式转换
                if (queryFiled.getString("showtype").equals("4") && conQueryObj.get(filed) != null) {
                    String value = conQueryObj.getString(filed);

                    Date date = fmt.parse(value);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);

                    // 获取查询分钟数
                    int minute = calendar.get(Calendar.MINUTE);

                    if (delayTime == 0){
                        // 根据分钟数计算余数
                        int remainder = minute % delayTime;
                        minute += remainder > 0 ? delayTime - remainder : 0;
                    }

                    // 设置查询时间
                    calendar.set(Calendar.MINUTE, minute);
                    conQueryObj.put(filed, fmt.format(calendar.getTime()));
                }
            }
        }
        return conQueryObj == null ? "" : conQueryObj.toString();
    }
}
